import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart'; // 用于 debugPrint

/// 网络状态变化回调类型
typedef NetworkCallback = void Function(ConnectivityResult status);

class NetworkHelper {
  // 单例模式
  static final NetworkHelper _instance = NetworkHelper._internal();
  factory NetworkHelper() => _instance;
  NetworkHelper._internal();

  // Connectivity 实例
  final Connectivity _connectivity = Connectivity();

  // 监听网络变化的订阅
  StreamSubscription<List<ConnectivityResult>>? _subscription;

  // 网络状态变更回调
  NetworkCallback? _onNetworkChange;

  // 记录当前的网络状态
  ConnectivityResult _lastStatus = ConnectivityResult.none;

  // 标记是否正在监听
  bool _isListening = false;

  /// 获取当前网络状态
  ConnectivityResult get currentStatus => _lastStatus;

  /// **开始监听网络状态**
  void startListening(NetworkCallback onNetworkChange) {
    if (_isListening) return; // 防止重复监听
    _isListening = true;
    _onNetworkChange = onNetworkChange;

    // 初始化当前网络状态
    _initConnectivity();

    // 订阅网络状态变化
    _subscription = _connectivity.onConnectivityChanged
        .distinct((a, b) => listEquals(a, b)) // 去重，避免重复触发
        .listen(
      (List<ConnectivityResult> result) {
        if (result.isNotEmpty) {
          _updateConnectionStatus(result.first);
        }
      },
      onError: (error) {
        print("网络状态监听失败: $error");
      },
    );
  }

  /// **停止监听，防止内存泄漏**
  void stopListening() {
    _subscription?.cancel();
    _subscription = null;
    _isListening = false;
  }

  /// **初始化当前网络状态**
  Future<void> _initConnectivity() async {
    try {
      List<ConnectivityResult> initialStatus = await _connectivity.checkConnectivity();
      if (initialStatus.isNotEmpty) {
        _updateConnectionStatus(initialStatus.first);
      }
    } on PlatformException catch (e) {
      print("网络状态初始化失败: $e");
    }
  }

  /// **更新网络状态并触发回调**
  void _updateConnectionStatus(ConnectivityResult result) {
    if (_lastStatus == result) return; // 避免重复回调
    _lastStatus = result;

    // 调试信息
    print('当前网络状态: $_lastStatus');

    // 触发回调
    _onNetworkChange?.call(result);
  }

  /// **释放资源，适用于 StatefulWidget 的 dispose()**
  void dispose() {
    stopListening();
  }
}
